package com.hx.vending.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hx.vending.bean.Dict;
import com.hx.vending.bean.Equipment;
import com.hx.vending.bean.Model;
import com.hx.vending.bean.Trails;
import com.hx.vending.bean.config.Constants;
import com.hx.vending.bean.entity.EquipmentDentity;
import com.hx.vending.bean.entity.EquipmentFlowcard;
import com.hx.vending.bean.entity.EquipmentVo;
import com.hx.vending.bean.entity.FlowDeteils;
import com.hx.vending.dao.*;
import com.hx.vending.mqtt.PushCallback;
import com.hx.vending.mqtt.RunnerSendMqtt;
import com.hx.vending.service.IEquipmentService;
import com.hx.vending.util.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2018/11/26.
 */
@Service
public class EquipmentServiceImpl implements IEquipmentService{

    @Autowired
    private EquipmentMapper equipmentMapper;
    @Resource
    private OnlineOrderMapper onlineOrderMapper;
    @Resource
    private GoodsConsumeMapper goodsConsumeMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private TrailsMapper trailsMapper;
    @Resource
    private DictMapper dictMapper;
    private static Logger logger = Logger.getLogger(PushCallback.class); // 获取logger实例


    @Override
    public List<Equipment> selectByFieldId(Integer fieldId) {

        return equipmentMapper.selectByFieldId(fieldId);
    }

    @Override
    public List<Equipment> selectByExample(Equipment equipment) {
        return equipmentMapper.selectByExample(equipment);
    }

    @Override
    public Model selectModelById(Integer eqModelId) {
        return equipmentMapper.selectModelById(eqModelId);
    }

    @Override
    public Equipment selectByPrimary(Equipment equipment) {
        return equipmentMapper.selectByPrimary(equipment);
    }

    @Override
    public Integer updateByPrimaryKeySelective(Equipment equipment) {
        return equipmentMapper.updateByPrimaryKeySelective(equipment);
    }

    @Override
    public Integer insertSelective(Equipment equipment) {
        return equipmentMapper.insertSelective(equipment);
    }

    @Override
    public Integer updateByEqipment(Equipment equipment) {
        return equipmentMapper.updateByEqipment(equipment);
    }

    @Override
    public List<Dict> selectDictByPid(Integer pid) {
        return equipmentMapper.selectDictByPid(pid);
    }

    @Override
    public Msg getEquipmentListByFieldId(final Map<String, Object> paramMap) {
        Map<String, EquipmentVo> resultMap = new TreeMap<String, EquipmentVo>();
        if (ToolUtil.isEmpty(paramMap.get("fieldId")) || ToolUtil.isEmpty(paramMap.get("startTime"))
                || ToolUtil.isEmpty(paramMap.get("endTime"))) {
            return Msg.fail().add("msg", "参数错误");
        }
        if (ToolUtil.isEmpty(paramMap.get("sort")) || ToolUtil.isEmpty(paramMap.get("rule"))) {
            return Msg.fail().add("msg", "排序参数错误");
        }
        //场地id
        Integer fieldId = Integer.parseInt(paramMap.get("fieldId").toString());
        //查询开始时间
        String startTime = paramMap.get("startTime").toString();
        //查看结束时间
        String endTime = paramMap.get("endTime").toString();

        //设备
        List<Map<String, Object>> equipmentList = equipmentMapper.selectEquipmentByFieldId(fieldId);
        //根据场地id查询每台设备线下收益(设备id，线下收益)
        List<Map<String, Object>> underLineMoneyResultList = onlineOrderMapper.selectUnderAmountByEquipmentId(fieldId, startTime, endTime);
        //根据场地查询每台设备线上收益（设备id ，线上收益）
        List<Map<String, Object>> onlineOrderResultList = onlineOrderMapper.getAmountByFieldId(fieldId, startTime, endTime);
        //根据场地id查询每个设备下的礼品消耗数
        List<Map<String, Object>> goodsCounsumeResultList = goodsConsumeMapper.getGoodsAmountListByFieldId(fieldId, startTime, endTime);
        //遍历设备
        for(Map<String, Object> map : equipmentList){
            if(ToolUtil.isNotEmpty(map) && ToolUtil.isNotEmpty(map.get("equipmentId"))){
                //存储到map中
                String equipmentId = map.get("equipmentId").toString();
                //编号
                Integer equipmentNumber = Integer.parseInt(map.get("equipmentNumber").toString());
                //设备视图对象
                EquipmentVo equipmentVo = new EquipmentVo();
                equipmentVo.setEquipmentId(equipmentId);
                equipmentVo.setEquipmentNumber(equipmentNumber);
                //放入返回的键值对对象中
                resultMap.put(equipmentId, equipmentVo);
            }
        }
        //线下收益
        for(Map<String,Object> map : underLineMoneyResultList){
            if(ToolUtil.isNotEmpty(map) && ToolUtil.isNotEmpty(map.get("equipmentId"))){
                //如果resultMap中已有该设备的Vo则直接取出
                EquipmentVo equipmentVo = resultMap.get(map.get("equipmentId"));
                Double doubleValue = Double.parseDouble(map.get("underLineAmount").toString());
                //线上投币总金额
                equipmentVo.setUnderLineAmount(doubleValue);
                //放入返回的键值对对象中
                resultMap.put(map.get("equipmentId").toString(), equipmentVo);
            }
        }
        //线上收益
        for(Map<String,Object> map:onlineOrderResultList){
            if(ToolUtil.isNotEmpty(map) && ToolUtil.isNotEmpty(map.get("equipmentId"))){
                //如果resultMap中已有该设备的Vo则直接取出
                EquipmentVo equipmentVo = resultMap.get(map.get("equipmentId"));
                Double doubleValue = Double.parseDouble(map.get("onlineOrderAmount").toString());
                equipmentVo.setOnlineOrderAmount(doubleValue);
                //合计投币总金额
                if(ToolUtil.isEmpty(equipmentVo.getOnlineOrderAmount()) && ToolUtil.isEmpty(equipmentVo.getUnderLineAmount())){
                    equipmentVo.setAmount(0D);
                }else if(ToolUtil.isEmpty(equipmentVo.getOnlineOrderAmount()) && ToolUtil.isNotEmpty(equipmentVo.getUnderLineAmount())){
                    equipmentVo.setAmount(0D + equipmentVo.getUnderLineAmount());
                }else if(ToolUtil.isNotEmpty(equipmentVo.getOnlineOrderAmount()) && ToolUtil.isNotEmpty(equipmentVo.getUnderLineAmount())){
                    equipmentVo.setAmount(equipmentVo.getOnlineOrderAmount() + equipmentVo.getUnderLineAmount());
                }else if(ToolUtil.isNotEmpty(equipmentVo.getOnlineOrderAmount()) && ToolUtil.isEmpty(equipmentVo.getUnderLineAmount())){
                    equipmentVo.setAmount(equipmentVo.getOnlineOrderAmount() + 0D);
                }
                //放入返回的键值对对象中
                resultMap.put(map.get("equipmentId").toString(), equipmentVo);
            }
        }
        //循环遍历goodsCounsumeResultList
        for(Map<String,Object> map:goodsCounsumeResultList){
            if(ToolUtil.isNotEmpty(map) && ToolUtil.isNotEmpty(map.get("equipmentId"))){
                //如果resultMap中已有该设备的Vo则直接取出
                EquipmentVo equipmentVo = resultMap.get(map.get("equipmentId"));
                //商品消耗总数
                equipmentVo.setGoodsAmount(new BigDecimal(map.get("goodsAmount").toString()));
                //商品消耗总金额
                equipmentVo.setGoodsConsumeAmount((Double.parseDouble(map.get("goodsCounsumeAmount").toString())));
                //放入返回的键值对对象中
                resultMap.put(map.get("equipmentId").toString(), equipmentVo);
            }
        }
        //迭代resultMap,对null的金额等进行0赋值
        for (String key : resultMap.keySet()) {
            //设备视图对象
            EquipmentVo equipmentVo = resultMap.get(key);

            if (null == equipmentVo.getAmount()) {
                equipmentVo.setAmount(0D);
            }
            if (null == equipmentVo.getUnderLineAmount()) {
                equipmentVo.setUnderLineAmount(0D);
            }
            if (null == equipmentVo.getGoodsAmount()) {
                equipmentVo.setGoodsAmount(new BigDecimal("0"));
            }
            if (null == equipmentVo.getGoodsConsumeAmount()) {
                equipmentVo.setGoodsConsumeAmount(0D);
            }
            if (null == equipmentVo.getOnlineOrderAmount()) {
                equipmentVo.setOnlineOrderAmount(0D);
            }
        }
        /**
         * 排序
         */
        //这里将map.entrySet()转换成list
        List<Map.Entry<String, EquipmentVo>> list = new ArrayList<>(resultMap.entrySet());
        //然后通过比较器来实现排序
        if (paramMap.get("sort").equals("amount")) {
            Collections.sort(list, new Comparator<Map.Entry<String, EquipmentVo>>() {
                //升序排序
                public int compare(Map.Entry<String, EquipmentVo> o1,
                                   Map.Entry<String, EquipmentVo> o2) {
                    if (paramMap.get("rule").equals("asc")) {
                        //升序
                        return o1.getValue().getAmount().compareTo(o2.getValue().getAmount());
                    } else {
                        //降序
                        return o2.getValue().getAmount().compareTo(o1.getValue().getAmount());
                    }
                }
            });
        } else if (paramMap.get("sort").equals("equipmentNumber")) {
            Collections.sort(list, new Comparator<Map.Entry<String, EquipmentVo>>() {
                //升序排序
                public int compare(Map.Entry<String, EquipmentVo> o1,
                                   Map.Entry<String, EquipmentVo> o2) {
                    if (paramMap.get("rule").equals("asc")) {
                        //升序
                        return o1.getValue().getEquipmentNumber().compareTo(o2.getValue().getEquipmentNumber());
                    } else {
                        //降序
                        return o2.getValue().getEquipmentNumber().compareTo(o1.getValue().getEquipmentNumber());
                    }
                }
            });
        }
        //返回list
        List<EquipmentVo> resultList = new ArrayList();
        for (Map.Entry<String, EquipmentVo> map : list) {
            resultList.add(map.getValue());
        }
        return Msg.success().add("resultList",resultList);
    }

    /*public Msg   */


    /**
     * 查询设备的轮播图轮播视频
     * @param equipmentId
     * @return
     */
    public Msg selectEquipmentWheelMessage(String equipmentId) {
        if (ToolUtil.isNotEmpty(equipmentId)) {
            Equipment equipment = new Equipment();
            equipment.setEquipmentId(equipmentId);
            Equipment selectEquipment = this.equipmentMapper.selectByPrimary(equipment);
            if (ToolUtil.isNotEmpty(selectEquipment)) {
                String [] picture = null;
                String [] video = null;
                if (ToolUtil.isNotEmpty(selectEquipment.getEquipmentPicture())) {
                    picture = selectEquipment.getEquipmentPicture().split(",");
                }
                if (ToolUtil.isNotEmpty(selectEquipment.getEquipmentVideo())) {
                    video = selectEquipment.getEquipmentVideo().split(",");
                }
                if (ToolUtil.isEmpty(picture)) {
                    picture = new String[0];
                }
                if (ToolUtil.isEmpty(video)) {
                    video = new String[0];
                }
                return Msg.success().add("picture", picture).add("video", video);
            }else {
                return Msg.fail();
            }
        }else {
            return Msg.fail();
        }
    }


    /**
     * 保存设备轮播图片
     * @param equipmentId
     * @param pictures
     * @return
     */
    public Msg updateEquipmentPicture(String equipmentId, String pictures) {

        if (ToolUtil.isNotEmpty(equipmentId)) {

//            if (pictures.lastIndexOf(",") == pictures.length() - 1) {
//                pictures = pictures.substring(0, pictures.length() - 1);
//            }

            //查询设备信息
            Equipment equipment = new Equipment();
            equipment.setEquipmentId(equipmentId);
            Equipment selectEquipment = this.equipmentMapper.selectByPrimary(equipment);

            if (ToolUtil.isEmpty(selectEquipment)) {
                return Msg.fail().add("msg", "设备不存在");
            }

            //将原来的无用的从阿里云删除(将原来的图片遍历，如果没有在新传入的里面就删除)
            String[] oldpic = selectEquipment.getEquipmentPicture().split(",");
            for (String pic: oldpic) {
                if (ToolUtil.isEmpty(pictures)) {
                    //空的，把以前的全删掉
                    AliyunOSSClientUtil.deleteObject(pic);
                }else {
                    if (!pictures.contains(pic)) {
                        AliyunOSSClientUtil.deleteObject(pic);
                    }
                }
            }

            equipment.setEquipmentPicture(pictures);

            int  i = this.equipmentMapper.updatePictureNull(equipment);

            if (i != 0) {

                //发送MQTT消息
                String fourNumber = ToolUtil.generateNonceStr(4);//随机数
                RunnerSendMqtt runnerSendMqtt = new RunnerSendMqtt();
                runnerSendMqtt.setMessage(equipmentId + "," + fourNumber + ",change");
                runnerSendMqtt.setRedisTemplate(redisTemplate);
                runnerSendMqtt.setTheme("ChangeBanner");
                runnerSendMqtt.setThreadName("刷新广告指令");
                runnerSendMqtt.setRedisKey("ChangeBanner-" + equipmentId);
                runnerSendMqtt.start();

                return Msg.success();
            }else {
                return Msg.fail().add("msg", "保存失败哦!!");
            }
        }else {
            return Msg.fail();
        }
    }


    /**
     * 删除设备轮播图片
     * @param equipmentId
     * @param pictures
     * @return
     */
    public Msg deleteEquipmentPicture(String equipmentId, String pictures) {
        if (ToolUtil.isNotEmpty(equipmentId) && ToolUtil.isNotEmpty(pictures)) {

            if (pictures.lastIndexOf(",") == pictures.length() - 1) {
                pictures = pictures.substring(0, pictures.length() - 1);
            }

            String[] pic = pictures.split(",");

            //查询设备信息
            Equipment equipment = new Equipment();
            equipment.setEquipmentId(equipmentId);
            Equipment selectEquipment = this.equipmentMapper.selectByPrimary(equipment);

            if (ToolUtil.isNotEmpty(selectEquipment) && ToolUtil.isNotEmpty(selectEquipment.getEquipmentPicture())) {
                //循环删除
                for (String picture: pic) {
                    if (selectEquipment.getEquipmentPicture().contains(picture)) {
                        //可能在中间,先去除中间的，才能去除最后的
                        equipment.setEquipmentPicture(selectEquipment.getEquipmentPicture().replace(picture + ",", ""));
                        //可能在最后
                        equipment.setEquipmentPicture(selectEquipment.getEquipmentPicture().replace("," + picture, ""));

                        //将图片从阿里云删除
                        AliyunOSSClientUtil.deleteObject(picture);
                    }
                }
            }

            if (ToolUtil.isNotEmpty(equipment.getEquipmentPicture()) && !selectEquipment.getEquipmentPicture().equals(equipment.getEquipmentPicture())) {
                int i = this.equipmentMapper.updateByPrimaryKeySelective(equipment);

                if (i != 0) {

                    //发送MQTT消息
                    String fourNumber = ToolUtil.generateNonceStr(4);//随机数
                    RunnerSendMqtt runnerSendMqtt = new RunnerSendMqtt();
                    runnerSendMqtt.setMessage(equipmentId + "," + fourNumber + ",change");
                    runnerSendMqtt.setRedisTemplate(redisTemplate);
                    runnerSendMqtt.setTheme("ChangeBanner");
                    runnerSendMqtt.setThreadName("刷新广告指令");
                    runnerSendMqtt.setRedisKey("ChangeBanner-" + equipmentId);
                    runnerSendMqtt.start();

                    return Msg.success();
                }else {
                    return Msg.fail().add("msg", "删除失败哦!!");
                }
            }

            return Msg.success();
        }else{
            return Msg.fail();
        }
    }


    /**
     * 停用设备
     * @param equipmentId
     * @return
     */
    public Msg discontinueEquipment(String equipmentId, String whetherUser) {
        if (ToolUtil.isNotEmpty(equipmentId)) {

            //是否有设备
            Equipment equipment = new Equipment();
            equipment.setEquipmentId(equipmentId);
            Equipment selectEquipment = this.equipmentMapper.selectByPrimary(equipment);

            if (ToolUtil.isNotEmpty(selectEquipment)) {

                String type = null;
                if (whetherUser.equals("usable")) {
                    type = "可用";
                }else if (whetherUser.equals("unusable")) {
                    type = "停用";
                }

                //发送MQTT消息
                RunnerSendMqtt runnerSendMqtt = new RunnerSendMqtt();
                runnerSendMqtt.setMessage(equipmentId + "," + "0000" + "," + whetherUser);
                runnerSendMqtt.setRedisTemplate(redisTemplate);
                runnerSendMqtt.setTheme("SetUse");
                runnerSendMqtt.setThreadName("设备" + type);
                runnerSendMqtt.setRedisKey("Useable-" + equipmentId);
                runnerSendMqtt.start();

                return Msg.success();
            }else {
                return Msg.fail();
            }
        }else {
            return Msg.fail();
        }
    }


    /**
     * 替换设备轮播图
     * @param equipmentId
     * @return
     */
    public Msg updateReplaceEquipmentPicture(String equipmentId) {

        return Msg.success();
    }

    @Override
    public int deleteEquipmentById(String equipmentId) {
        return equipmentMapper.deleteEquipmentById(equipmentId);
    }

    @Override
    public List<EquipmentDentity> selectByExamplePage(String equipmentId, String equipmentType, String userName, Integer equipmentUseCondition,
                                                      Integer equipmentState, Integer pageNum) {
        return equipmentMapper.selectByExamplePage(equipmentId,equipmentType,userName,equipmentUseCondition,equipmentState,pageNum);
    }

    @Override
    public Integer selectEquipmentNum(String equipmentId, String equipmentType, String userName, Integer equipmentUseCondition, Integer equipmentState) {
        return equipmentMapper.selectEquipmentNum(equipmentId,equipmentType,userName,equipmentUseCondition,equipmentState);
    }

    @Override
    public int updateEquipmentVideo(Equipment equipment) {
        return equipmentMapper.updateEquipmentVideo(equipment);
    }

    @Override
    public int updateEquipmentByUserId(Integer userId) {
        return equipmentMapper.updateEquipmentByUserId(userId);
    }


    /**
     * 设备货道测试
     * @param equipmentId    设备id
     * @param trailsId       货道id
     * @return
     */
    @Override
    public Msg equipmentTrailsTest(String equipmentId, Integer trailsId, Integer caseNumber) {
        if (ToolUtil.isEmpty(equipmentId)) {
            return Msg.fail().add("msg", "设备id为空");
        }

        //查询货道
        Trails trails = new Trails();
        if (ToolUtil.isNotEmpty(trailsId)) {
            //货道id不为空，只测试当前货道
            trails.setTrailsId(trailsId);
        }else {
            //货道id和箱柜编号为空，测试整个机器的货道
            trails.setTrailsEquipmentId(equipmentId);

            if (ToolUtil.isNotEmpty(caseNumber)) {
                //货道id为空，箱柜编号不为空，查箱柜
                trails.setTrailsCaseId(caseNumber);
            }
        }
        List<Trails> trailsList = this.trailsMapper.selectByExampleSelective(trails);

        if (ToolUtil.isNotEmpty(trailsList)) {

            //发送测试货道的MQTT消息
            RunnerSendMqtt runnerSendMqtt = new RunnerSendMqtt();
            runnerSendMqtt.setMessage(equipmentId);
            runnerSendMqtt.setRedisTemplate(redisTemplate);
            runnerSendMqtt.setTheme("TestMouth");
            runnerSendMqtt.setThreadName("货到测试指令");
            runnerSendMqtt.setRedisKey("TestMouthReceive-" + equipmentId);
            runnerSendMqtt.setTrailsList(trailsList);
            runnerSendMqtt.start();
            return Msg.success();
        }else {
            return Msg.fail().add("msg", "货道不存在");
        }
    }

    @Override
    public List<Equipment> selectByFieldIds(Integer[] integers) {
        return equipmentMapper.selectByFieldIds(integers);
    }


    /**
     * 查询设备流量卡的信息
     * @param userId             用户id
     * @param equipmentId        设备id（传查当前设备的）
     * @param type               类型0查询最近七天   1查询当月的(默认查最近七天的)
     * @return
     */
    @Override
    public Msg selectEquipmentFlowcard(Integer userId, String equipmentId, Integer type) {

        if (ToolUtil.isEmpty(userId)) {
            return Msg.fail().add("msg", "用户未登录");
        }

        //查询设备信息
        Equipment equipment = new Equipment();
        equipment.setEquipmentUserId(userId);
        if (ToolUtil.isNotEmpty(equipmentId)) {
            equipment.setEquipmentId(equipmentId);
        }
        List<Equipment> equipmentList = this.equipmentMapper.selectByExample(equipment);

        if (equipmentList.size() == 0) {
            return Msg.fail().add("msg", "设备不存在或未注册");
        }

        if (equipmentList.size() == 1) {
            if (ToolUtil.isEmpty(equipmentList.get(0).getEquipmentFlowcard())) {
                return Msg.fail().add("msg", "设备物联卡不存在");
            }
        }

        //保存返回信息
        List<EquipmentFlowcard> equipmentFlowcards = new ArrayList<EquipmentFlowcard>();
        //Authorization所需用户密码
        String authorization = Base64Util.baseEncode(Constant.IOTCARD_APPKEY+":"+Constant.IOTCARD_APPSECRET);//base64一行不能超过76字符，超过则添加回车换行符
        authorization = authorization.replaceAll("[\\s*\\t\\n\\r]", "");

        //循环设备列表
        for (Equipment equi: equipmentList) {
            EquipmentFlowcard equipmentFlowcard = new EquipmentFlowcard();
            equipmentFlowcard.setEquipmentId(equi.getEquipmentId());
            if (ToolUtil.isNotEmpty(equi.getEquipmentFlowcard()) && equi.getEquipmentFlowcard() != "") {
                //有流量卡
                equipmentFlowcard.setFlowcardYON(0);

                //////////////查询物流卡信息////////////
                Map<String, Object> cardMap = new HashMap<>();
                cardMap.put("imsi", equi.getEquipmentFlowcard());
                Map<String, Object> cardResultMap = SendRequest.SendFlowRequest(Constant.IOTCARD_CARD, cardMap, "POST", authorization);
                if (ToolUtil.isNotEmpty(cardResultMap)) {
                    if (cardResultMap.get("code").toString().equals("0")) {
                        String cardJsonStr = cardResultMap.get("data").toString();
                        cardJsonStr = cardJsonStr.replace("[", "");
                        cardJsonStr = cardJsonStr.replace("]", "");
                        Map<String, Object> cardResultDataMap = (Map<String, Object>) JSONObject.parse(cardJsonStr);

                        equipmentFlowcard.setFlowDatabalance(cardResultDataMap.get("data_balance").toString());//剩余流量
                        equipmentFlowcard.setFlowDataplan(cardResultDataMap.get("data_plan").toString());//套餐大小
                        equipmentFlowcard.setFlowDatausage(cardResultDataMap.get("data_usage").toString());//当月用量
                    }
                }

                //////////////查询流量消耗//////////////
                //要传的值
                Map<String, Object> paramsMap = new HashMap<>();
                paramsMap.put("imsis", equi.getEquipmentFlowcard());
                //时间
                Date date = new Date();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                //时间装换
                SimpleDateFormat sdf;
                SimpleDateFormat sdfday = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat sdfmonth = new SimpleDateFormat("yyyy-MM");

                //接收返回信息
                Map<String, Object> resultMap = new HashMap<>();
                List<FlowDeteils> flowDeteilss = new ArrayList<FlowDeteils>();

                if (type == 0) {
                    //查询七天的(当天的试了不能查)
                    sdf = new SimpleDateFormat("yyyyMMdd");
                    for (int i = 0; i < 7; i++) {
//                        if (i != 0) {
                            calendar.add(Calendar.DATE, -1);
//                        }
                        paramsMap.put("query_date", sdf.format(calendar.getTime()));
                        resultMap = SendRequest.SendFlowRequest(Constant.IOTCARD_URL, paramsMap, "POST", authorization);
                        if (ToolUtil.isNotEmpty(resultMap)) {
                            if (resultMap.get("code").toString().equals("0")) {
                                FlowDeteils flowDeteils = new FlowDeteils();
                                flowDeteils.setFlowDate(sdfday.format(calendar.getTime()));

                                String jsonStr = resultMap.get("data").toString();
                                jsonStr = jsonStr.replace("[", "");
                                jsonStr = jsonStr.replace("]", "");
                                Map<String, Object> resultDataMap = (Map<String, Object>) JSONObject.parse(jsonStr);
                                flowDeteils.setFlowConsume(resultDataMap.get("data_usage").toString());

                                flowDeteilss.add(flowDeteils);
                            }
                        }
                    }
                }else if (type == 1) {
                    //查询当月的
                    sdf = new SimpleDateFormat("yyyyMM");
                    paramsMap.put("query_month", sdf.format(calendar.getTime()));
                    resultMap = SendRequest.SendFlowRequest(Constant.IOTCARD_MONTHLY_URL, paramsMap, "POST", authorization);
                    if (ToolUtil.isNotEmpty(resultMap)) {
                        if (resultMap.get("code").toString().equals("0")) {
                            FlowDeteils flowDeteils = new FlowDeteils();
                            flowDeteils.setFlowDate(sdfmonth.format(calendar.getTime()));

                            String jsonStr = resultMap.get("data").toString();
                            jsonStr = jsonStr.replace("[", "");
                            jsonStr = jsonStr.replace("]", "");
                            Map<String, Object> resultDataMap = (Map<String, Object>) JSONObject.parse(jsonStr);
                            flowDeteils.setFlowConsume(resultDataMap.get("data_usage").toString());

                            flowDeteilss.add(flowDeteils);
                        }
                    }
                }

                equipmentFlowcard.setAllFlowConsume(flowDeteilss);
                equipmentFlowcard.setFlowcardIMSI(equi.getEquipmentFlowcard());

            }else {
                //没有流量卡
                equipmentFlowcard.setFlowcardYON(1);

            }
            equipmentFlowcards.add(equipmentFlowcard);
        }

        return Msg.success().add("flowcardMsg", equipmentFlowcards);
    }


    /**
     * 查询物联卡的使用情况（后台查询）
     * @return
     */
    @Override
    public Msg selctFlowcardUserCondition() {

        //Authorization所需用户密码
        String authorization = Base64Util.baseEncode(Constant.IOTCARD_APPKEY+":"+Constant.IOTCARD_APPSECRET);//base64一行不能超过76字符，超过则添加回车换行符
        authorization = authorization.replaceAll("[\\s*\\t\\n\\r]", "");

        //查询计费组列表
        Map<String, Object> resultMap = SendRequest.SendFlowRequest(Constant.IOTCARD_BILLING_GROUP, new HashMap(), "POST", authorization);

        //获取计费组信息
        List<Map<String, Object>> billingGroupList = null;
        if (ToolUtil.isNotEmpty(resultMap)) {
            if (resultMap.get("code").toString().equals("0")) {
                billingGroupList = (List<Map<String, Object>>) JSONObject.parse(resultMap.get("data").toString());
            }
        }

        if (ToolUtil.isEmpty(billingGroupList)) {
            return Msg.fail().add("msg", "获取计费组失败或无计费组");
        }

        Double totalFlowPool = 0.00;//总流量池
        Double flowConsume = 0.00;//流量消耗
        Double surplusFlow = 0.00;//剩余流量

        //根据计费组的bg_code查询流量
        for (Map group: billingGroupList) {

            //查询该计费组下的物联卡信息(需要判断页码)
            A:for (int i = 1; i > 0; i++) {
                Map<String, Object> paramsMap = new HashMap<>();
                paramsMap.put("bg_code", group.get("bg_code"));//流量组编号
                paramsMap.put("page", i);//页码
                paramsMap.put("psize", 100);//数量
                Map<String, Object> cardListMap = SendRequest.SendFlowRequest(Constant.IOTCARD_CARDLIST, paramsMap, "POST", authorization);
                if (ToolUtil.isNotEmpty(cardListMap)) {
                    if (cardListMap.get("code").toString().equals("0")) {
                        //获得所有卡的集合
                        List<Map<String, Object>> allCardMsg = (List<Map<String, Object>>) JSONObject.parse(cardListMap.get("data").toString());

                        totalFlowPool += BigDecimalUtils.mul(allCardMsg.size(), Double.parseDouble(allCardMsg.get(0).get("data_plan").toString()));

                        //循环所有卡
                        for (Map card: allCardMsg) {
                            surplusFlow += Double.parseDouble(card.get("data_balance").toString());
                        }

                        //判断页码(当前页大于等于总页数跳出循环)
                        if (Integer.parseInt(cardListMap.get("page").toString())>=Integer.parseInt(cardListMap.get("num_pages").toString())) {
                            break A;
                        }
                    }
                }
            }
        }
        return Msg.success().add("totalFlowPool", totalFlowPool).add("surplusFlow", surplusFlow);
    }



    /**
     * Android保存截屏图片
     * @param file
     * @param equipmentId
     * @return
     */
    @Override
    public Msg uploadScreenshotPicture(MultipartFile[] file, String equipmentId) {

        if (ToolUtil.isEmpty(equipmentId)) {
            return Msg.fail().add("msg", "该设备不存在");
        }

        if (ToolUtil.isEmpty(file) && file.length <= 0) {
            return Msg.fail().add("msg", "未上传文件");
        }

        Equipment equipment = new Equipment();
        equipment.setEquipmentId(equipmentId);
        Equipment selectEquipment = this.equipmentMapper.selectByPrimary(equipment);
        if (ToolUtil.isEmpty(selectEquipment)) {
            return Msg.fail().add("msg", "该设备不存在");
        }

        String imgurl = null;
        //图片上传到阿里云
        for (int i = 0; i < file.length; i++) {
            if (!file[i].isEmpty()) {
                //上传图片
                imgurl=AliyunOSSClientUtil.handleUploadFile(file[i], "android/screenshot/");
                if(imgurl!=null&&imgurl.length()>0){
                    //先将原来的删除
                    if (ToolUtil.isNotEmpty(selectEquipment.getEquipmentShot())) {
                        AliyunOSSClientUtil.deleteObject(selectEquipment.getEquipmentShot());
                    }
                    //将图片保存到数据库
                    equipment.setEquipmentShot(imgurl);
                    this.equipmentMapper.updateByPrimaryKeySelective(equipment);

                    //上传完成
                    redisTemplate.boundValueOps("ShotUploadOK-" + equipmentId).set(imgurl, Constants.MQTT_EXPIRES_HOUR, TimeUnit.SECONDS);
                }
            }
        }

        return Msg.success().add("imgurl", imgurl);
    }


    /**
     * 请求获取Android截屏图片
     * @param equipmentId
     * @param userId
     * @return
     */
    @Override
    public Msg requestScreenshotPicture(String equipmentId, Integer userId) {

        if (ToolUtil.isEmpty(userId)) {
            return Msg.fail().add("msg", "用户未登录");
        }

        if (ToolUtil.isEmpty(equipmentId)) {
            return Msg.fail().add("msg", "该设备不存在");
        }

        Equipment equipment = new Equipment();
        equipment.setEquipmentId(equipmentId);
        equipment.setEquipmentUserId(userId);
        Equipment selectEquipment = this.equipmentMapper.selectByPrimary(equipment);

        if (ToolUtil.isEmpty(selectEquipment)) {
            return Msg.fail().add("msg", "该设备不存在");
        }

        String fourNumber = ToolUtil.generateNonceStr(4);//随机数
        B:for (int j = 0; j < 8; j++) {

            //发送指令
            try {
                redisTemplate.delete("ShotUploadOK-" + equipmentId);
                PubMsg.publish(equipmentId + "," + fourNumber + ",shot", "UploadShot/" + equipmentId);

                C:for (int getMsg = 0; getMsg < 5; getMsg++) {
                    Thread.sleep(1000);
                    //获取缓存数据
                    String redisMessage = redisTemplate.boundValueOps("UploadShot-" + equipmentId).get();

                    if (null != redisMessage) {

                        String[] msg = redisMessage.split(",");
                        if (equipmentId.equals(msg[0]) && msg[1].equals(fourNumber)) {//接收到了消息

                            //看截图是否上传成功
                            for (int shot = 0; shot < 30; shot++) {
                                Thread.sleep(1000);
                                String shotUpload = redisTemplate.boundValueOps("ShotUploadOK-" + equipmentId).get();

                                if (ToolUtil.isNotEmpty(shotUpload)) {


                                    System.out.println("验证消息成功");

                                    redisTemplate.delete("UploadShot-" + equipmentId);
                                    redisTemplate.delete("ShotUploadOK-" + equipmentId);

                                    return Msg.success().add("imgurl", shotUpload);
                                }
                            }
                            break C;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        return Msg.fail();
    }


    /**
     * 调节设备音量
     * @param equipmentId       设备id
     * @param type              raise/lower
     * @return
     */
    @Override
    public Msg equipmentAdjustVolume(String equipmentId, String type) {
        if (ToolUtil.isEmpty(equipmentId)) {
            return Msg.fail().add("msg", "设备不存在");
        }

        if (ToolUtil.isEmpty(type)) {
            return Msg.fail().add("msg", "请选择音量增加或减少");
        }

        Equipment equipment = new Equipment();
        equipment.setEquipmentId(equipmentId);
        Equipment selectEquipment = this.equipmentMapper.selectByPrimary(equipment);

        if (ToolUtil.isEmpty(selectEquipment)) {
            return Msg.fail().add("msg", "设备不存在");
        }

        //发送MQTT消息
        String fourNumber = ToolUtil.generateNonceStr(4);//随机数

        String audio = null;
        B:for (int j = 0; j < 8; j++) {

            //发送指令
            try {
                PubMsg.publish(equipmentId + "," + fourNumber + "," + type, "AdjustAudio/" + equipmentId);

                for (int getMsg = 0; getMsg < 5; getMsg++) {
                    Thread.sleep(1000);
                    //获取缓存数据
                    String redisMessage = redisTemplate.boundValueOps("AdjustAudio-" + equipmentId).get();

                    if (null != redisMessage) {

                        String[] msg = redisMessage.split(",");
                        if (equipmentId.equals(msg[0]) && msg[1].equals(fourNumber)) {//接收到了消息

                            System.out.println("验证消息成功");
                            audio = msg[2];

                            redisTemplate.delete("AdjustAudio-" + equipmentId);

                            break B;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (ToolUtil.isEmpty(audio)) {
            return Msg.fail();
        }

        //保存音量
        equipment.setEquipmentAudio(audio);
        this.equipmentMapper.updateByPrimaryKeySelective(equipment);

        return Msg.success().add("audio", audio);
    }


    /**
     * 获取设备音量
     * @param equipmentId
     * @return
     */
    @Override
    public Msg selectEquipmentAudio(String equipmentId) {
        if (ToolUtil.isEmpty(equipmentId)) {
            return Msg.fail().add("msg", "设备不存在");
        }

        Equipment equipment = new Equipment();
        equipment.setEquipmentId(equipmentId);
        Equipment selectEquipment = this.equipmentMapper.selectByPrimary(equipment);

        if (ToolUtil.isEmpty(selectEquipment)) {
            return Msg.fail().add("msg", "设备不存在");
        }
        return Msg.success().add("audio", selectEquipment.getEquipmentAudio());
    }

    @Override
    public Msg uploadPhoto(MultipartFile[] file, String equipmentId) {
        Equipment equipment = equipmentMapper.selectById(equipmentId);
        Equipment e = new Equipment();
        e.setEquipmentId(equipmentId);
        if(ToolUtil.isEmpty(equipment)){
            return Msg.fail().add("msg","该设备不存在");
        }
        if (ToolUtil.isEmpty(file) && file.length <= 0) {
            return Msg.fail().add("msg", "未上传文件");
        }
        String imgurl = null;
        for(int i = 0;i < file.length;i++){
            if(ToolUtil.isNotEmpty(file[i])){
                //上传图片
                imgurl=AliyunOSSClientUtil.handleUploadFile(file[i], "android/equipment/");
                if(ToolUtil.isNotEmpty(imgurl)){
                    //先将原来的删除
                    if (ToolUtil.isNotEmpty(equipment.getEquipmentCamera())) {
                        AliyunOSSClientUtil.deleteObject(equipment.getEquipmentCamera());
                    }
                    //将图片保存到数据库
                    e.setEquipmentCamera(imgurl);
                    this.equipmentMapper.updateByPrimaryKeySelective(e);

                    //上传完成
                    redisTemplate.boundValueOps("PhotoUploadOK-" + equipmentId).set(imgurl, Constants.MQTT_EXPIRES_HOUR, TimeUnit.SECONDS);
                }
            }
        }
        return Msg.success().add("imgurl",imgurl);
    }

    @Override
    public Msg requestEquipmentCamera(String equipmentId,Integer userId){
        Equipment equipment = equipmentMapper.selectById(equipmentId);
        if(ToolUtil.isEmpty(equipment)){
            return Msg.fail().add("msg","该设备不存在");
        }
        String fourNumber = ToolUtil.generateNonceStr(4);//随机数
        B:for (int j = 0; j < 8; j++) {

            //发送指令
            try {
                redisTemplate.delete("PhotoUploadOK-" + equipmentId);
                PubMsg.publish(equipmentId + "," + fourNumber + ",", "UploadPhoto/" + equipmentId);

                C:for (int getMsg = 0; getMsg < 5; getMsg++) {
                    Thread.sleep(1000);
                    //获取缓存数据
                    String redisMessage = redisTemplate.boundValueOps("UploadPhoto-" + equipmentId).get();

                    if (null != redisMessage) {

                        String[] msg = redisMessage.split(",");
                        if (equipmentId.equals(msg[0]) && msg[1].equals(fourNumber)) {//接收到了消息


                            //看截图是否上传成功
                            for (int shot = 0; shot < 30; shot++) {
                                Thread.sleep(1000);
                                String photoUpload = redisTemplate.boundValueOps("ShotUploadOK-" + equipmentId).get();

                                if (ToolUtil.isNotEmpty(photoUpload)) {
                                    System.out.println("验证消息成功");

                                    redisTemplate.delete("UploadPhoto-" + equipmentId);
                                    redisTemplate.delete("PhotoUploadOK-" + equipmentId);

                                    return Msg.success().add("imgurl", photoUpload);
                                }
                            }
                            break C;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Msg.fail();
    }


    /**
     * 线下支付统计设备余币
     * @param equipmentId
     * @param coins
     * @return
     */
    @Override
    public Msg updateEquipmentCoin(String equipmentId, Integer coins) {

        if (ToolUtil.isEmpty(equipmentId)) {
            return Msg.fail().add("msg", "未获取设备id");
        }

        if (ToolUtil.isEmpty(coins)) {
            return Msg.fail().add("msg", "未获取币数");
        }

        Equipment equipment = new Equipment();
        equipment.setEquipmentId(equipmentId);
        Equipment selectEquipment = this.equipmentMapper.selectByPrimary(equipment);

        if (ToolUtil.isEmpty(selectEquipment)) {
            return Msg.fail().add("msg", "设备不存在");
        }

        Integer allCoins = selectEquipment.getEquipmentCoin() - coins;

        if (allCoins < 0) {
            allCoins = 0;
        }

        equipment.setEquipmentCoin(allCoins);

        int  i = this.equipmentMapper.updateByPrimaryKeySelective(equipment);

        if (i != 0) {
            return Msg.success();
        }else {
            return Msg.fail();
        }

    }



    /**
     * 修改设备总余币数
     * @param equipmentId
     * @param coins
     * @return
     */
    @Override
    public Msg updateEquipmentCoinCount(String equipmentId, Integer coins) {
        if (ToolUtil.isEmpty(equipmentId)) {
            return Msg.fail().add("msg", "未获取设备id");
        }

        if (ToolUtil.isEmpty(coins)) {
            return Msg.fail().add("msg", "未获取币数");
        }

        Equipment equipment = new Equipment();
        equipment.setEquipmentId(equipmentId);
        Equipment selectEquipment = this.equipmentMapper.selectByPrimary(equipment);

        if (ToolUtil.isEmpty(selectEquipment)) {
            return Msg.fail().add("msg", "设备不存在");
        }

        equipment.setEquipmentCoin(coins);

        int i = this.equipmentMapper.updateByPrimaryKeySelective(equipment);

        if (i != 0) {
            return Msg.success();
        }else {
            return Msg.fail();
        }
    }


}
